package cn.edu.njuit.server.ugcnote.ugcnoteserver.apis;

import cn.edu.njuit.server.ugcnote.ugcnoteserver.entity.UserInfo;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.service.AccountService;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.security.TokenService;
import com.alibaba.fastjson.JSONObject;

import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class AccountApi {
    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    private final TokenService tokenService;
    private final AccountService accountService;
    public AccountApi(AuthenticationManagerBuilder authenticationManagerBuilder, TokenService tokenService, AccountService accountService) {
        this.authenticationManagerBuilder = authenticationManagerBuilder;
        this.tokenService = tokenService;
        this.accountService = accountService;
    }

    @PostMapping("/login")
    public ResponseEntity doLogin(@RequestParam(required = true)String login,
                                  @RequestParam(required = true)String password){

        //使用用户传入的登录名密码，构造Security的登录名密码认证对象UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(login,password);
        try{
            //2、使用SpringSecurity的验证器对用户身份进行校验authenticate()
            Authentication authentication =
                    authenticationManagerBuilder.getObject().authenticate(authenticationToken);
            //SpringSecurity验证通过后，得到已认证对象authentication，从已认证对象中读取账户数据。
            User authenticatedUser=(User)authentication.getPrincipal();
            //通过用户名获得令牌
            String token=this.tokenService.getToken(authenticatedUser.getUsername());
            JSONObject result=new JSONObject();
            result.put("id_token",token);
            return ResponseEntity.ok(result);
        }catch (Exception e){
            //发生异常表示登录出错
            return ResponseEntity.status(401).body("用户名密码错误");
        }
    }

    @PostMapping("/regist")
    public ResponseEntity registerAccount(@RequestParam(required = true)String login,
                                          @RequestParam(required = true)String password,
                                          @RequestParam(required = true)String nickname,
                                          @RequestParam(required = false,defaultValue = "role_user")String defaultRole) {
        try {
            UserInfo account=this.accountService.regAccount(login,password,nickname);
            return ResponseEntity.ok(account);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(400).body(e.getMessage());
        }
    }
}
